import { App } from "../../../../src/App";
import { EventConst } from "../../../../src/core/EventConst";
import { GameModule } from "../Game/GameModule";

const { menu, ccclass, property } = cc._decorator;
@ccclass
@menu("斗地主/窗体组件/设置")
export default class SetView extends cc.Component {
    @property(cc.Toggle)
    btnSound: cc.Toggle = null;
    @property(cc.Toggle)
    btnMusic: cc.Toggle = null;
    @property(cc.Label)
    lblExitBtn: cc.Label = null;
    @property(cc.Label)
    lblVersion: cc.Label = null;

    private _vol = {sound:1,music:1};
    private _localSet: any;

    start() {
        this._localSet = App.getLocalStorage(App.LOCAL_KEY.AUDIO);
        this.btnSound.isChecked = this._localSet.sound > 0;
        this.btnSound.node.getChildByName('Background').active = !this.btnSound.isChecked;
        this.btnMusic.isChecked = this._localSet.music > 0;
        this.btnMusic.node.getChildByName('Background').active = !this.btnMusic.isChecked;
        this._vol = App.Audio.getVolumes();
        let _str = App.getText('landlord.set_view_buttons');
        const _strs = _str.split('|');
        this.lblExitBtn.string = _strs[GameModule.isPlaying ? 2:(GameModule.isInRoom?1:0)];
        this.lblVersion.string = App.Util.format(App.getText('version'),App.getCfg('modules/master/version'));//`${App.getText('version')}${App.getCfg('modules/master/version')}`;
    };

    onExitClick(){
        if (GameModule.isInRoom){
            !GameModule.isPlaying && App.runScene('HallScene:hall');
        } else {
            App.MessageBox(App.getText('exit_app'),(flag:number)=>{
                flag === App.MB_FLAG.OK && cc.game.end();
            });
        }
    }

    onChangeLoginClick(){
        if (GameModule.isPlaying){
            App.popTips(App.getText('landlord.game_progress'));
            return ;
        } else {
            App.MessageBox(App.getText('logout'),(flag:number)=>{
                if (flag === App.MB_FLAG.OK){
                    App.closeView(this.node);
                    GameModule.logout();
                }
            });
        }
    }

    onSwitchClicket(sender,dt){
        sender.node.getChildByName('Background').active = !sender.isChecked;
        const vol = sender.isChecked ? 1:0;
        if (dt === 'sound'){
            this._vol.sound = vol;
            App.Audio.setVolume(this._vol.music,vol);
        }

        if (dt === 'music'){
            this._vol.music = vol;
            App.Audio.setVolume(vol, this._vol.sound);
        }
    }

    onClearClick(){
        App.MessageBox(App.getText('clear_cache'),(flag)=>{
            if (flag === App.MB_FLAG.OK) {
                cc.sys.isNative && jsb.fileUtils.removeDirectory(App.Native.getWritablePath());
                cc.sys.localStorage.clear();
                cc.audioEngine.stopAll();
                cc.game.restart();
            }
        });
	}
}